package com.bawei.module_mine.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_goods.entity.ShoppingCartDisplayItem
import com.bawei.module_mine.R
import com.bumptech.glide.Glide

class ConfirmOrderProductAdapter(
    private val items: MutableList<ShoppingCartDisplayItem>,
    private val onCountChange: ((position: Int, newCount: Int) -> Unit)? = null
) : RecyclerView.Adapter<ConfirmOrderProductAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val ivGoodsImage: ImageView = view.findViewById(R.id.ivGoodsImage)
        val tvGoodsName: TextView = view.findViewById(R.id.tvGoodsName)
        val tvGoodsSpec: TextView = view.findViewById(R.id.tvGoodsSpec)
        val tvGoodsPrice: TextView = view.findViewById(R.id.tvGoodsPrice)
        val tvGoodsCount: TextView = view.findViewById(R.id.tvGoodsCount)
        val btnMinus: TextView = view.findViewById(R.id.btnMinus)
        val btnAdd: TextView = view.findViewById(R.id.btnAdd)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_cart_goods, parent, false)
        view.findViewById<View>(R.id.checkboxItem)?.visibility = View.GONE
        view.findViewById<View>(R.id.layoutCount)?.visibility = View.VISIBLE
        view.findViewById<View>(R.id.btnMinus)?.visibility = View.VISIBLE
        view.findViewById<View>(R.id.btnAdd)?.visibility = View.VISIBLE
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        holder.tvGoodsName.text = item.goodsName ?: "-"
        holder.tvGoodsSpec.text = "规格：${item.goodsSkuId ?: "-"}"
        holder.tvGoodsPrice.text = "￥${item.price ?: 0.0}"
        holder.tvGoodsCount.text = item.number.toString()
        Glide.with(holder.ivGoodsImage.context)
            .load(item.goodsImage)
            .placeholder(R.mipmap.ic_launcher)
            .into(holder.ivGoodsImage)
        holder.btnMinus.setOnClickListener {
            if (item.number > 1) {
                onCountChange?.invoke(position, item.number - 1)
            }
        }
        holder.btnAdd.setOnClickListener {
            onCountChange?.invoke(position, item.number + 1)
        }
    }

    override fun getItemCount(): Int = items.size

    fun updateItemCount(position: Int, newCount: Int) {
        if (position in items.indices) {
            items[position] = items[position].copy(number = newCount)
            notifyItemChanged(position)
        }
    }

    fun getItems(): List<ShoppingCartDisplayItem> = items
} 